﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CLEX.Service.DataContracts;
using CLEX.Service.ServiceContracts;

namespace CLEX.Service.Proxies
{
    public class ClientCache : IClientCache
    {
        private readonly IClientService proxy;

        public event Action<DatabaseData> DatabaseCreated;
        public event Action<DatabaseData> DatabaseDeleted;
        public event Action<DatabaseData> DatabaseUpdated;

        public ClientCache(IClientService proxy)
        {
            this.proxy = proxy;
        }

        public UserData Login(string username, string password)
        {
            return proxy.Login(username, password);
        }

        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            return proxy.ChangePassword(username, oldPassword, newPassword);
        }

        public List<DatabaseData> GetDatabasesByUserId(int userId)
        {
            return proxy.GetDatabasesByUserId(userId);
        }

        public int CreateDatabase(int userId, string connectionString)
        {
            int id = proxy.CreateDatabase(userId, connectionString);
            RaiseDatabaseCreated(new DatabaseData(id, userId, connectionString));
            return id;
        }

        public void DeleteDatabase(int databaseId)
        {
            var database = proxy.GetDatabase(databaseId);
            proxy.DeleteDatabase(databaseId);
            RaiseDatabaseDeleted(database);
        }

        public void UpdateDatabase(DatabaseData database)
        {
            proxy.UpdateDatabase(database);
            RaiseDatabaseUpdated(database);
        }

        public DatabaseData GetDatabase(int databaseId)
        {
            return proxy.GetDatabase(databaseId);
        }

        public List<TableData> GetSchema(string connectionString)
        {
            return proxy.GetSchema(connectionString);
        }

        public List<HistogramRowData> ComputeHistograms(string connectionString, QueryData queryData)
        {
            return proxy.ComputeHistograms(connectionString, queryData);
        }

        private void RaiseDatabaseCreated(DatabaseData database)
        {
            var handler = DatabaseCreated;
            if (handler != null)
            {
                handler(database);
            }
        }

        private void RaiseDatabaseDeleted(DatabaseData database)
        {
            var handler = DatabaseDeleted;
            if (handler != null)
            {
                handler(database);
            }
        }

        private void RaiseDatabaseUpdated(DatabaseData database)
        {
            var handler = DatabaseUpdated;
            if (handler != null)
            {
                handler(database);
            }
        }
    }
}
